$(function () {
	// 获取用户数据
	var id = sessionStorage.getItem("id");
	var token = sessionStorage.getItem("token");

	axios
		.get(`http://localhost:9000/users/info?id=${id}`, {
			headers: {
				Authorization: token,
			},
		})
		.then(({ data }) => {
			if (data.code === 1) {
				document.querySelector(".username").value = data.user.username;
				document.querySelector(".age").value = data.user.age||"";
				document.querySelector(".gender").value = data.user.gender;
				document.querySelector(".nickname").value = data.user.nickname;
			}
		})
		.catch(error => console.error("Error:", error));

	// 表单验证
	document.querySelector("form").addEventListener("submit", function (event) {
		event.preventDefault(); // 阻止表单默认提交

		var username = document.querySelector('input[name="username"]').value;
		var age = document.querySelector('input[name="age"]').value;
		var gender = document.querySelector('select[name="gender"]').value;
		var nickname = document.querySelector('input[name="nickname"]').value;

		// 简单的前端验证
		if (!username || !age || !gender || !nickname) {
			alert("请填写所有必填项");
			return;
		}

		axios("http://localhost:9000/users/update", {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				Authorization: token,
			},
			data: JSON.stringify({
				id: id,
				age: age,
				gender: gender,
				nickname: nickname,
			}),
		})
			.then(response => {
				if (response.data.code === 1) {
					alert(response.data.message);
					sessionStorage.setItem("nickname", nickname);
				} else {
					alert(response.data.message);
				}
			})
			.catch(error => console.error("error:", error));
	});
});
